package com.yupi.springbootinit.controller.WxminiApp;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.user.Wxmini.WxUserLoginRequest;
import com.yupi.springbootinit.model.dto.user.Wxmini.WxUserRegisterRequest;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.service.WxminiAppService;
import com.yupi.springbootinit.service.impl.Miniapp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @Author xingyu Xue
 * @Date 2024/4/13 16:56
 */
@RestController
@RequestMapping("/wxminiapp")
@Slf4j
@Api(value = "微信小程序用户接口")
public class WxminiAppUserController {

    private final WxMaService wxMaService;

    //构造器注入WxMaService 依赖
    @Autowired
    public WxminiAppUserController(WxMaService wxMaService) {
        this.wxMaService = wxMaService;
    }

    @Value("${wx.miniapp.configs[0].appid}")
    private String appid;
    @Autowired
    private WxminiAppService wxminiAppService;
    @Autowired
    private Miniapp miniapp;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "小程序登录")
    @PostMapping("/login")
    public BaseResponse<UserVO> wxlogin(@RequestBody WxUserLoginRequest wxUserLoginRequest, HttpServletRequest request) {

        String code = wxUserLoginRequest.getCode();


        if (StringUtils.isBlank(code)) {
            return new BaseResponse("empty jscode");
        }
        //判断appid是否存在
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }


        try {
            //向腾讯接口发送code请求，
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            String openid = session.getOpenid();
            String sessionKey = session.getSessionKey();
            String unionid = session.getUnionid();
            log.info("sessionKey:{}", sessionKey);
            log.info("openid:{}", openid);
            log.info("unionid:{}", unionid);
            //TODO 可以增加自己的逻辑，关联业务相关数据
            UserVO wxlogin = wxminiAppService.wxlogin(openid,request);



            return new BaseResponse(200, wxlogin, "用户登录成功！");


//            WxUserVo miniloginVO = userService.miniLogin(openid, sessionKey);
            //生成返回给小程序的token
//            Map map = new HashMap();
//            map.put("token",miniloginVO.getOpenid());

//            String token = JwtUtil.genToken(map);
//            if (token!=null){
//                log.info("token:{}",token);
//            }


//            return new BaseResponse<>(200,token,"登录成功");


        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return new BaseResponse(e.toString());

//            return e.toString();
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }


//        wxminiapp.wxlogin();

//        WxUserVo wxUserVo=new WxUserVo();
//        wxUserVo.setUserName("薛星宇");
//        wxUserVo.setUserRole("user");
//        wxUserVo.setMemberShip("11142532637345345");
//        wxUserVo.setPhoneNumber("15698443151");
//
//        return new BaseResponse(200,wxUserVo,"用户登录成功！");

    }


    @ApiOperation(value = "注册接口")
    @PostMapping("/register")
    public BaseResponse<UserVO> register(@RequestBody WxUserRegisterRequest user, HttpServletRequest request) {
        String username = user.getUsername();
        String phonenumber = user.getPhonenumber();
        String password = user.getPassword();
        String code = user.getCode();
        String checkpassword = user.getCheckpassword();

        //判断四个参数是否有空值
        if (StringUtils.isBlank(username) || StringUtils.isBlank(phonenumber) || StringUtils.isBlank(password) || StringUtils.isBlank(code) || StringUtils.isBlank(checkpassword)) {
            return new BaseResponse(500,"empty params","参数有空");
        }
        String openid = miniapp.isLogin(code);
        //密码两次不一样
        if (!password.equals(checkpassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User register = wxminiAppService.register(username, phonenumber, password, openid,request);
        UserVO userVO = userService.getUserVO(register);


        return new BaseResponse<>(200, userVO, "注册成功！");
    }


    @ApiOperation(value = "获取用户信息接口")
    @PostMapping("/getuser")
    public BaseResponse<UserVO> getUserInfo(@RequestBody String code, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        UserVO userVO = userService.getUserVO(loginUser);
        return new BaseResponse<>(200, userVO, "获取用户信息成功！");
    }


}
